#!/usr/bin/python
# -*- coding:utf-8 -*-
import logging
from logging.handlers import TimedRotatingFileHandler

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

from config import config_dict

# db
db = SQLAlchemy()

# login
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.auth_login'


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_dict[config_name])

    # 初始化
    db.init_app(app)
    login_manager.init_app(app)

    # 蓝图
    from .actions.main import main as main_blueprint
    from .actions.auth import auth as auth_blueprint
    from .actions.blog import blog as blog_blueprint
    from .actions.category import category as category_blueprint
    from .actions.tag import tag as tag_blueprint
    from .actions.user import user as user_blueprint
    from .actions.menu import menu as menu_blueprint

    app.register_blueprint(main_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    app.register_blueprint(blog_blueprint, url_prefix='/blog')
    app.register_blueprint(category_blueprint, url_prefix='/category')
    app.register_blueprint(tag_blueprint, url_prefix='/tag')
    app.register_blueprint(user_blueprint, url_prefix='/user')
    app.register_blueprint(menu_blueprint, url_prefix='/menu')

    # 其他

    # 日志
    handler = TimedRotatingFileHandler('logs/app.log', when='D', backupCount=7, encoding='UTF-8')
    handler.setLevel(logging.INFO)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)

    return app
